<template>
  <el-dialog
    :visible.sync="visible"
    :title="!dataForm.id ? $t('add') : $t('update')"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="close()"
    :destroy-on-close="true"
    @opened="opened()"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmitHandle()"
      :label-width="$i18n.locale === 'en-US' ? '140px' : '130px'"
      :disabled="disabled"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名" prop="touristName">
            <el-input v-model="dataForm.touristName" placeholder="姓名"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="身份证号" prop="card">
            <el-input v-model="dataForm.card" placeholder="身份证号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="dataForm.phone" placeholder="手机号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入园时间" prop="enterDate">
            <el-date-picker
              style="width: 100%"
              value-format="yyyy-MM-dd HH:mm:ss"
              v-model="dataForm.enterDate"
              type="datetime"
              placeholder="入园时间"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="门票类型" prop="type">
            <SelectComponent
              ref="type"
              dictType="tourist_type"
              v-model="dataForm.type"
              placeholder="门票类型"
            >
            </SelectComponent>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="订单类型" prop="orderType">
            <SelectComponent
              ref="orderType"
              dictType="tourist_order_type"
              v-model="dataForm.orderType"
              placeholder="订单类型"
            >
            </SelectComponent>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="地址" prop="province">
            <el-select
              v-model="dataForm.province"
              :placeholder="disabled ? '' : '省编码'"
              clearable
              style="width: 14%"
              @change="
                (val) => {
                  regionChange(val, 'province');
                }
              "
            >
              <el-option
                v-for="item in provinceOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="dataForm.city"
              :placeholder="disabled ? '' : '市'"
              clearable
              style="width: 14%; margin: 0 1%"
              @change="
                (val) => {
                  regionChange(val, 'city');
                }
              "
            >
              <el-option
                v-for="item in cityOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="dataForm.area"
              :placeholder="disabled ? '' : '区'"
              clearable
              style="width: 14%"
              @change="
                (val) => {
                  regionChange(val, 'area');
                }
              "
            >
              <el-option
                v-for="item in areaOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
            <el-input
              style="width: 14%; margin: 0 1%"
              v-model="dataForm.street"
              :placeholder="disabled ? '' : '街道'"
            ></el-input>
            <el-input
              v-model="dataForm.areaDetail"
              :placeholder="disabled ? '' : '详细地址'"
              style="width: 40%"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{
        $t("confirm")
      }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from "lodash/debounce";
import mixinRegionModule from "@/mixins/region-module";
import { isIdCard, isMobile } from "@/utils/validate";

export default {
  mixins: [mixinRegionModule],
  data() {
    return {
      visible: false,
      dataForm: {
        id: "",
        touristName: "",
        card: "",
        phone: "",
        enterDate: "",
        province: "",
        city: "",
        area: "",
        street: "",
        areaDetail: "",
        type: "",
        status: "",
        remark: "",
        delFlag: "",
        creator: "",
        createDate: "",
        updater: "",
        updateDate: "",
      },
    };
  },
  props: {
    disabled: Boolean,
  },
  computed: {
    dataRule() {
      var validatePhone = (rule, value, callback) => {
        if (value.indexOf("**") > -1) {
          value = value.replace(/\*/g, "5");
        }
        if (!isMobile(value)) {
          return callback(
            new Error(
              this.$t("validate.format", { attr: this.$t("user.mobile") })
            )
          );
        }
        callback();
      };
      var validateCard = (rule, value, callback) => {
        if (value.indexOf("**") > -1) {
          value = value.replace(/\*/g, "1");
        }
        if (!isIdCard(value)) {
          return callback(new Error("身份证号格式不正确"));
        }
        callback();
      };
      return {
        touristName: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        card: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
          { validator: validateCard, trigger: "blur" },
        ],
        phone: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
          { validator: validatePhone, trigger: "blur" },
        ],
      };
    },
  },
  created() {
    this.provincAreaDetailInfoList();
  },
  watch: {
    // "this.dataForm.province": {
    //   immediate: true,
    //   deep: true,
    //   handler(newVal) {
    //     this.cityAreaDetailInfoList(newVal);
    //   },
    // },
    // "this.dataForm.city": {
    //   immediate: true,
    //   deep: true,
    //   handler(newVal) {
    //     this.countyAreaDetailInfoList(newVal);
    //   },
    // },
  },
  methods: {
    opened() {
      this.provincAreaDetailInfoList();
      if (this.dataForm.city) {
        this.cityAreaDetailInfoList(this.dataForm.province);
      }
      if (this.dataForm.area) {
        this.countyAreaDetailInfoList(this.dataForm.city);
      }
    },
    close() {
      this.dataForm = {
        id: "",
        touristName: "",
        card: "",
        phone: "",
        enterDate: "",
        province: "",
        city: "",
        area: "",
        street: "",
        areaDetail: "",
        type: "",
        status: "",
        remark: "",
        delFlag: "",
        creator: "",
        createDate: "",
        updater: "",
        updateDate: "",
        //脱敏处理
        tempName: "",
        tempCard: "",
        tempPhone: "",
      };
      this.$emit("changeDisabled");
    },
    init() {
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.getInfo();
        }
      });
    },
    // 获取信息
    getInfo() {
      this.$http
        .get("/sys/istourist/" + this.dataForm.id)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.dataForm = {
            ...this.dataForm,
            ...res.data,
          };
          //加密备用
          this.dataForm.tempName = this.dataForm.touristName;
          this.dataForm.tempCard = this.dataForm.card;
          this.dataForm.tempPhone = this.dataForm.phone;
          this.dataForm.orderType = this.dataForm.orderType + "";
          this.dataForm.type = this.dataForm.type + "";
          this.$refs.orderType.selectValue = this.dataForm.orderType;
          this.$refs.type.selectValue = this.dataForm.type;
        })
        .catch(() => {});
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs["dataForm"].validate((valid) => {
          if (!valid) {
            return false;
          }
          //加密
          let newDataForm = Object.assign({}, this.dataForm);
          if (newDataForm.touristName || newDataForm.tempName != newDataForm.touristName) {
            //编辑了
            newDataForm.touristName = this.$CryptoJS.encrypt(newDataForm.touristName);
          } else {
            newDataForm.touristName = null;
          }
          if (!newDataForm.card || newDataForm.tempCard != newDataForm.card) {
            newDataForm.card = this.$CryptoJS.encrypt(newDataForm.card);
          } else {
            newDataForm.card = null;
          }
          if (
            !newDataForm.phone ||
            newDataForm.tempPhone != newDataForm.phone
          ) {
            newDataForm.phone = this.$CryptoJS.encrypt(newDataForm.phone);
          } else {
            newDataForm.phone = null;
          }
          this.$http[!newDataForm.id ? "post" : "put"](
            "/sys/istourist/",
            newDataForm
          )
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              this.$message({
                message: this.$t("prompt.success"),
                type: "success",
                duration: 500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            })
            .catch(() => {});
        });
      },
      1000,
      {
        leading: true,
        trailing: false,
      }
    ),
  },
};
</script>
